//
//  TopicDetailViewController.m
//  BeautyClother
//
//  Created by dllo on 15/8/28.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "TopicDetailViewController.h"
#import "define.h"
#import "UIImageView+WebCache.h"
#import "AsyncConnection.h"
#import "LunbotuDetailTableViewCell.h"
#import "LunbotuDetailViewController.h"
#import "ImageSaveViewController.h"
#import "CommentCell.h"


@interface TopicDetailViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, assign) NSInteger num;
@property (nonatomic, assign) CGFloat offHeigt;
@property (nonatomic, assign) CGFloat offWidth;
@property (nonatomic, retain) NSDictionary *dic;

@end

@implementation TopicDetailViewController

- (void)dealloc
{
    [_dic release];
    [_arr release];
    [_table release];
    [_array release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        self.offHeigt = [[UIScreen mainScreen]bounds].size.height / 667;
        self.offWidth = [[UIScreen mainScreen]bounds].size.width / 375;
        self.dic = [NSDictionary dictionary];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self beginConnection];
    [self createTableView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"f.png"] style:UIBarButtonItemStyleDone target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor darkGrayColor];
    // Do any additional setup after loading the view.
}

- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)beginConnection
{
    NSDictionary *dic = @{@"token":@"A2C8A7F0-5A1D-4614-9F42-9455C27499CB",
                          @"topicid":self.tid,
                          @"ua":@"iPhone%7C1.7.11",
                          @"lang":@"en",
                          @"sig":@"bffdd7757c2d1440727248030",
                          @"nt":@"wifi"};
    
    [AsyncConnection asyncConnection:LUNBOTU_WEB parmaters:dic block:^(NSData *data) {
        self.dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.array = [_dic objectForKey:@"content"];
        [self.table reloadData];
    }path:self.tid];
}

- (void)createTableView
{
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 69, self.view.frame.size.width, self.view.frame.size.height - 70) style:UITableViewStylePlain];
    [self.view addSubview:self.table];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.table release];
    [self createView];
}

- (void)createView
{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 70 * _offHeigt)];
    [self.table addSubview:header];
    header.frame = CGRectMake(0, 0, self.view.frame.size.width, 70 * _offHeigt);
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(10 *_offWidth, 10 * _offHeigt, 50 *_offWidth, 50 *_offHeigt)];
    [header addSubview:image];
    image.layer.cornerRadius = 50 *_offWidth / 2;
    image.layer.masksToBounds = YES;
    [image sd_setImageWithURL:[NSURL URLWithString:[self.dic objectForKey:@"publisherIcon"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
    [image release];
    
    UILabel *userName = [[UILabel alloc]initWithFrame:CGRectMake(60 * _offWidth, 10 *_offHeigt, 150 * _offWidth, 25 * _offHeigt)];
    [header addSubview:userName];
    userName.text = [self.dic objectForKey:@"publisherName"];
    [userName release];
    
    UILabel *sign = [[UILabel alloc]initWithFrame:CGRectMake(60 * _offWidth, 35 *_offHeigt, 250 * _offWidth, 25 * _offHeigt)];
    [header addSubview:sign];
    sign.textColor = [UIColor lightGrayColor];
    sign.font = [UIFont systemFontOfSize:14];
    sign.text = [self.dic objectForKey:@"publisherSign"];
    [sign release];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{
    return 5;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
        
    
    if (self.array.count == 0) {
        return 0;
    }else
    {
    
    return self.array.count;
    }
    }else
    {
        return 1;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section != 0) {
        
    
    if (indexPath.row == 0) {
        CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"uuu"];
        if (cell == nil) {
            cell = [[CommentCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"uuu"];
        }
        
    }
    
    if ([[[[self.array objectAtIndex:indexPath.row]objectForKey:@"type"]stringValue] isEqualToString:@"2"]) {
       UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"text"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"text"];
        }
        cell.textLabel.numberOfLines = 0;
        
        cell.textLabel.text = [@"🌲  " stringByAppendingString:[[self.array objectAtIndex:indexPath.row]objectForKey:@"text"]];
        
        return cell;
    }
    if ([[[[self.array objectAtIndex:indexPath.row]objectForKey:@"type"]stringValue] isEqualToString:@"1"])
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"1"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:@"%ld", indexPath.row + indexPath.section]];
            
        }
        
        CGFloat height = [[[self.array objectAtIndex:indexPath.row]objectForKey:@"imgHei"]floatValue];
        CGFloat width = [[[self.array objectAtIndex:indexPath.row]objectForKey:@"imgWid"]floatValue];
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width * height / width)];
        image.userInteractionEnabled = YES;
        image.tag = indexPath.row;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(save:)];
        [image addGestureRecognizer:tap];
        [tap release];
        [cell.contentView addSubview:image];
        [image sd_setImageWithURL:[NSURL URLWithString:[[self.array objectAtIndex:indexPath.row]objectForKey:@"imgURL"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        
        return cell;
    }
    if ([[[[self.array objectAtIndex:indexPath.row]objectForKey:@"type"]stringValue] isEqualToString:@"3"]) {
        self.num = 0;
        self.num = indexPath.row;
        self.arr = [[self.array objectAtIndex:indexPath.row]objectForKey:@"itemList"];
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"%ld", indexPath.row]];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:@"%ld", indexPath.row]];
            
        for (int i = 0; i < _arr.count; i ++) {
            
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake((i % 2) * self.view.frame.size.width / 2, (i / 2) * 180 * _offHeigt, self.view.frame.size.width / 2, 150* _offHeigt)];
            image.tag =  i;
            image.userInteractionEnabled = YES;
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(itemDetail4:)];
            [image addGestureRecognizer:tap];
            
            
            [cell.contentView addSubview:image];
            [image sd_setImageWithURL:[NSURL URLWithString:[[[[self.array objectAtIndex:indexPath.row]objectForKey:@"itemList"]objectAtIndex:i] objectForKey:@"imgURL"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
            UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(i % 2 * self.view.frame.size.width / 2, (i / 2) * 180* _offHeigt + 150* _offHeigt, self.view.frame.size.width / 2, 30* _offHeigt)];
            [cell.contentView addSubview:title];
            title.textAlignment = 1;
            title.text = [[[[self.array objectAtIndex:indexPath.row]objectForKey:@"itemList"]objectAtIndex:i]objectForKey:@"brand"];
            [image release];
            [title release];
            
        }
        }
        return cell;
    }else
    {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cut"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:@"%ld", indexPath.row]];
            
        }
        for (int i = 0; i < 3; i++) {
            UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(10*_offWidth + 120*_offWidth * i, 10* _offHeigt, 110*_offWidth, 100* _offHeigt)];
            [cell.contentView addSubview:image];
            [image sd_setImageWithURL:[NSURL URLWithString:[[[[self.array objectAtIndex:indexPath.row]objectForKey:@"tripleList"]objectAtIndex:i]objectForKey:@"imgURL"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
            
            image.tag = i + indexPath.row;
            image.userInteractionEnabled = YES;
            if (image.tag == indexPath.row + 0) {
                UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(itemDetail:)];
                [image addGestureRecognizer:tap1];
                [tap1 release];
            }
            if (image.tag == 1 + indexPath.row) {
                UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(itemDetail1:)];
                [image addGestureRecognizer:tap2];
                [tap2 release];
            }
            if (image.tag == 2 + indexPath.row) {
                UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(itemDetail2:)];
                [image addGestureRecognizer:tap3];
                [tap3 release];
            }
        [image release];
        }
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10*_offWidth, 105* _offHeigt, self.view.frame.size.width - 20*_offWidth, 25* _offHeigt)];
        [cell.contentView addSubview:label];
        label.textAlignment = 1;
        label.text = [[self.array objectAtIndex:indexPath.row]objectForKey:@"tripleTitle"];
        [label release];
    
        return cell;
    
    }
    }else
    {
        [self createView];
        return [[[UITableViewCell alloc]init]autorelease];
    }
}

- (void)save:(UITapGestureRecognizer *)save
{
    ImageSaveViewController *iiii = [[ImageSaveViewController alloc]init];
    iiii.image = ((UIImageView *)save.view).image;
    CGFloat height = [[[self.array objectAtIndex:save.view.tag]objectForKey:@"imgHei"]floatValue];
    CGFloat width = [[[self.array objectAtIndex:save.view.tag]objectForKey:@"imgWid"]floatValue];
    iiii.width = width;
    iiii.height = height;
    [self.navigationController pushViewController:iiii animated:YES];
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 70 * _offHeigt;
    }
    
    if ([[[[self.array objectAtIndex:indexPath.row]objectForKey:@"type"]stringValue] isEqualToString:@"2"]) {
        return [[self class]heightWithText:[[self.array objectAtIndex:indexPath.row]objectForKey:@"text"]];
    }
    if ([[[[self.array objectAtIndex:indexPath.row]objectForKey:@"type"]stringValue] isEqualToString:@"1"]) {
        CGFloat height = [[[self.array objectAtIndex:indexPath.row]objectForKey:@"imgHei"]floatValue];
        CGFloat width = [[[self.array objectAtIndex:indexPath.row]objectForKey:@"imgWid"]floatValue];
        return self.view.frame.size.width * height / width;
    }
    if ([[[[self.array objectAtIndex:indexPath.row]objectForKey:@"type"]stringValue] isEqualToString:@"3"]) {
        return ((NSArray *)[[self.array objectAtIndex:indexPath.row]objectForKey:@"itemList"]).count / 2 * 180* _offHeigt;
    }
    else
    {
        return 150 * _offHeigt;
    }
    
}

#pragma mark -
#pragma mark - 计算文字高度
+ (CGFloat)heightWithText:(NSString *)text
{
    // 参数1: 预定的矩形大小
    // 参数2: 图形选项
    // 参数3: 属性字典(设置字体大小, 一般和cell中的设置成一样的)
    // 参数4: 内容文本 一般设置为空nil
    CGRect rect = [text boundingRectWithSize:CGSizeMake(280 * [[UIScreen mainScreen]bounds].size.width / 375, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
    return rect.size.height;
}


- (void)itemDetail:(UITapGestureRecognizer *)tap
{
    LunbotuDetailViewController *itemDetail = [[LunbotuDetailViewController alloc]init];
    itemDetail.iid = [[[[self.array objectAtIndex:tap.view.tag ]objectForKey:@"tripleList"]objectAtIndex:0]objectForKey:@"itemId"];
    itemDetail.sig = @"55e4b9701ab21440742027406";
    [self.navigationController pushViewController:itemDetail animated:YES];
    [itemDetail release];
}

- (void)itemDetail1:(UITapGestureRecognizer *)tap
{
    LunbotuDetailViewController *itemDetail = [[LunbotuDetailViewController alloc]init];
    itemDetail.iid = [[[[self.array objectAtIndex:tap.view.tag - 1]objectForKey:@"tripleList"]objectAtIndex:1]objectForKey:@"itemId"];
    itemDetail.sig = @"55e4b9701ab21440742027406";
    [self.navigationController pushViewController:itemDetail animated:YES];
    [itemDetail release];
}



- (void)itemDetail2:(UITapGestureRecognizer *)tap
{
    LunbotuDetailViewController *itemDetail = [[LunbotuDetailViewController alloc]init];
    itemDetail.iid = [[[[self.array objectAtIndex:tap.view.tag - 2]objectForKey:@"tripleList"]objectAtIndex:2]objectForKey:@"itemId"];
    itemDetail.sig = @"55e4b9701ab21440742027406";
    [self.navigationController pushViewController:itemDetail animated:YES];
    [itemDetail release];
}

- (void)itemDetail4:(UITapGestureRecognizer *)tap
{
    LunbotuDetailViewController *itemDetail = [[LunbotuDetailViewController alloc]init];
    itemDetail.iid = [[[[self.array objectAtIndex:self.num]objectForKey:@"itemList"]objectAtIndex:tap.view.tag]objectForKey:@"itemId"];
    itemDetail.sig = @"6677dfd28d081440751309812";
    [self.navigationController pushViewController:itemDetail animated:YES];
    [itemDetail release];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
